module StorageSystem
  require 'net/ftp'
  require 'net/http'
  
  # CLASS FtpStorage: Handles requests that require a FTP connection
  class FtpStorage
    def initialize(host, user = 'anonymous', password = nil)
      @host = host
      @user = user
      @password = password
    end
  
    # Get an object from a FTP server
    def get(object, local_path = nil, remote_path = nil)
      local_path = local_path.to_s
    
      Net::FTP.open(@host) do |ftp|
        begin
          ftp.login(@user, @password)
          ftp.chdir(remote_path) unless remote_path.nil?
          ftp.get(object, local_path + object)
          true
        rescue Net::FTPPermError
          File.delete(local_path + object) if File.exist?(local_path + object)
          raise FileNotStoredException.new
          false
        end
      end
    end
  
    # Put an object in the FTP server
    def put(object, local_path = nil, remote_path = nil)
      local_path = local_path.to_s
      return false if !File.exist?(local_path + object)
  
      Net::FTP.open(@host) do |ftp|
        begin
          ftp.login(@user, @password)
          ftp.chdir(remote_path) unless remote_path.nil?
          ftp.put(local_path + object, object)
          true
        rescue Net::FTPPermError
          raise FileNotStoredException.new
        end
      end
    end
  end
  
  # CLASS HttpStorage: Handles requests that requires a HTTP connection
  class HttpStorage
    def initialize(host, port = nil)
      @host = host
      @port = port
    end
  
    def get(object, local_path = nil, remote_path = nil)
      begin
        url = URI.parse(@host)
        response = Net::HTTP.start(url.host, url.port) {|http|
          http.get(remote_path.to_s + object)
        }
      
        File.open(local_path.to_s + object, "w+") { |file|
          file << response
        }
        true
      rescue Exception
        Time.now.to_s + ' Impossible to obtain file from host "' + @host + '". File: ' + remote_path.to_s + object
        raise
        false
      end
    end
  
    def put(object, local_path = nil, remote_path = nil)
    end
  end

  class SMBStorage
    def initialize(path_to_host)
      @host = path_to_host
    end
    
    def put(object, local_path = nil)
      local_path = local_path.to_s
      return false if !File.exist?(local_path + object)

    end
  end

  # Custom Exception
  class FileNotStoredException < Exception
  end
end